package tron;

import java.awt.FlowLayout;

import javax.swing.*;

public class Game {
    Field field;
    FieldPanel fieldPanel;
    boolean isServer;
    Server sna;
    Client cna;
    int numOfSnake;

    public Game(int size, int countOfSnakes, boolean isServer) {
	this.isServer = isServer;
	field = new Field(size, countOfSnakes);
	fieldPanel = new FieldPanel(field);
	fieldPanel.setLayout(new FlowLayout());

	JFrame frame = new JFrame();
	frame.setLayout(new FlowLayout());
	frame.add(fieldPanel);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.addKeyListener(new Control(this));
	frame.pack();
	frame.setVisible(true);

	if (isServer) {
	    numOfSnake = 1;
	    sna = new Server(this, field, fieldPanel);
	} else {
	    numOfSnake = 2;
	    cna = new Client(this, field, fieldPanel);
	}
    }

    public void setDirection(Snake.Direction direction) {
	Snake snake = field.getSnake(numOfSnake);

	if (snake != null)
	    snake.setDirection(direction);
	System.out.println("Set " + snake);
    }

    public void games() throws InterruptedException {
	while (true) {
	    field.init();
	    oneGame();
	}
    }

    public void setField(Field field) {
	this.field = field;
	fieldPanel.field = field;
    }

    private void oneGame() throws InterruptedException {
	if (isServer) {
	    this.sna.startServer();
	} else {
	    System.out.println("start " + field.getSnake(numOfSnake).direction);
	    this.cna.startClient();

	}
    }

    public static void main(String argv[]) throws InterruptedException {

	boolean server = false;
	if (argv.length > 0)
	    server = true;
	int size = 50;
	int countOfSnakes = 2;

	Thread thServer = new Thread(new testServer());
	Thread thClient = new Thread(new testClient());
	thServer.start();
	thClient.start();

	thServer.join();
	thClient.join();
	System.out.println("qqqqqq");
    }
}
